﻿<script setup lang="ts" name="AbTestB">
import { addResizeListener, removeResizeListener } from '@/utils/resize'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
const route = useRoute()
const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)
const resizeDom = ref()
const itemWidth = ref(0)
const itemHeight = ref(0)
const update = () => {
  itemWidth.value = resizeDom.value.offsetWidth
  itemHeight.value = resizeDom.value.offsetHeight
}
// 获取当前页面的缓存状态是否被开启
const isKeepAlive = route.meta.keepAlive && systemConfig.value.isKeepAlive
// 在组件挂载到页面后执行
onMounted(() => {
  // 未开启页面状态缓存的情况下，监听事件在此声明周期内开启
  if (!isKeepAlive) {
    addResizeListener(unref(resizeDom), update)
  }
})
// 页面未启用keep-alive时，则需要在此生命周期函数内（组件被卸载之前执行）移除监听
onBeforeUnmount(() => {
  // 未开启页面状态缓存的情况下，监听事件在此声明周期内移除
  if (!isKeepAlive) {
    removeResizeListener(unref(resizeDom), update)
  }
})

// keep-alive启用时，页面被激活时使用
onActivated(() => {
  // 开启页面状态缓存的情况下，监听事件在此声明周期内开启
  if (isKeepAlive) {
    addResizeListener(unref(resizeDom), update)
  }
})
// 页面启用keep-alive时，则需要在此生命周期函数内（组件切换，老组件消失的时候执行）移除监听事件
onDeactivated(() => {
  // 开启页面状态缓存的情况下，监听事件在此声明周期内移除
  if (isKeepAlive) {
    removeResizeListener(unref(resizeDom), update)
  }
})
</script>

<template>
  <el-space :size="systemConfig.space" fill direction="vertical">
    <el-card shadow="never" class="no-border no-radius">
      <div ref="resizeDom" class="resize-container">
        <p>监听元素宽高变化: 宽：{{ itemWidth }}、高：{{ itemHeight }}</p>
      </div>
    </el-card>
  </el-space>
</template>

<style scoped lang="scss">
.el-space {
  width: 100%;
  padding: var(--el-space) var(--el-space) 0;
}

.no-border {
  border: none;
}

.no-radius {
  border-radius: 0;
}

.el-card {
  display: flex;

  :deep(.el-card__body) {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .resize-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;

      p {
        font-weight: bold;
        font-size: 24px;
        text-align: center;
      }
    }
  }
}
</style>
